import http.server
import json
import logging
import os
import socketserver
import threading
import time

# 配置日志
logging.basicConfig(
    level=os.environ.get('LOG_LEVEL', 'INFO'),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("logs/health_check.log"),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger('health_check')

# 全局状态
service_status = {
    "status": "starting",
    "uptime": 0,
    "start_time": time.time(),
    "components": {
        "gold_thread": False,
        "other_metals_thread": False,
        "kafka_producer": False,
        "iotdb_connection": False,
        "batch_processor": False
    },
    "metrics": {
        "requests_total": 0,
        "kafka_messages_sent": 0,
        "db_records_processed": 0,
        "errors": 0
    }
}

class HealthCheckHandler(http.server.SimpleHTTPRequestHandler):
    """处理健康检查HTTP请求的处理器"""
    
    def do_GET(self):
        """处理GET请求"""
        if self.path == '/health':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            
            # 更新运行时间
            service_status["uptime"] = int(time.time() - service_status["start_time"])
            
            # 检查所有组件，决定整体状态
            components = service_status["components"]
            is_healthy = all(components.values())
            
            if service_status["status"] == "starting" and is_healthy:
                service_status["status"] = "healthy"
            elif service_status["status"] != "starting" and not is_healthy:
                service_status["status"] = "unhealthy"
            
            # 发送状态响应
            self.wfile.write(json.dumps(service_status).encode())
            logger.debug("Health check request served")
        elif self.path == '/metrics':
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            
            # 生成Prometheus格式的指标
            metrics = []
            metrics.append(f'# HELP price_server_up 服务是否在运行')
            metrics.append(f'# TYPE price_server_up gauge')
            metrics.append(f'price_server_up {1 if service_status["status"] in ["healthy", "starting"] else 0}')
            
            metrics.append(f'# HELP price_server_uptime_seconds 服务运行时间（秒）')
            metrics.append(f'# TYPE price_server_uptime_seconds counter')
            metrics.append(f'price_server_uptime_seconds {service_status["uptime"]}')
            
            # 添加组件状态
            for component, status in service_status["components"].items():
                metrics.append(f'# HELP price_server_component_{component} 组件状态')
                metrics.append(f'# TYPE price_server_component_{component} gauge')
                metrics.append(f'price_server_component_{component} {1 if status else 0}')
            
            # 添加指标数据
            for metric, value in service_status["metrics"].items():
                metrics.append(f'# HELP price_server_{metric} {metric}')
                metrics.append(f'# TYPE price_server_{metric} counter')
                metrics.append(f'price_server_{metric} {value}')
            
            self.wfile.write('\n'.join(metrics).encode())
        else:
            self.send_response(404)
            self.end_headers()
    
    def log_message(self, format, *args):
        """覆盖日志方法以防止控制台垃圾输出"""
        return

def update_component_status(component, status):
    """更新组件状态"""
    if component in service_status["components"]:
        service_status["components"][component] = status

def increment_metric(metric, value=1):
    """增加指标计数"""
    if metric in service_status["metrics"]:
        service_status["metrics"][metric] += value

def start_health_check_server(port=8000):
    """启动健康检查HTTP服务器"""
    try:
        handler = HealthCheckHandler
        httpd = socketserver.ThreadingTCPServer(("", port), handler)
        
        logger.info(f"健康检查服务器在端口 {port} 上启动")
        
        # 在后台线程中启动服务器
        server_thread = threading.Thread(target=httpd.serve_forever, daemon=True)
        server_thread.start()
        
        return httpd
    except Exception as e:
        logger.error(f"启动健康检查服务器失败: {e}")
        return None

# 如果直接运行此文件，则启动服务器
if __name__ == "__main__":
    httpd = start_health_check_server()
    try:
        # 模拟主程序运行
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        httpd.shutdown()
        logger.info("健康检查服务器已关闭") 